import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String severIP, int port) throws IOException {
        socket = new Socket(severIP, port);
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scanner1 = new Scanner(inputStream);
            while (true) {
                //1.读取用户输入的内容
                System.out.printf("->");
                String request = scanner.next();
                //2.构造成请求发送过去（带有换行）
                printWriter.println(request);
                //数据写入缓存区，满了才会写网卡，需要手动刷新缓冲区
                printWriter.flush();
                //3.从服务器读取响应
                String reponse = scanner1.next();
                //4.结果显示
                System.out.printf("req:%s;resp:%s\n",request,reponse);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}